package lv.solcraft.replication.server.rest.restlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.List;

import lv.solcraft.replication.server.api.ServerFacade;
import lv.solcraft.replication.server.bdb.DbMaintenance;
import net.sf.json.JSONArray;

import org.apache.log4j.Logger;
import org.restlet.Context;
import org.restlet.data.CharacterSet;
import org.restlet.data.Encoding;
import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.ChannelRepresentation;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;

import com.noelios.restlet.application.EncodeRepresentation;
import com.sleepycat.je.DatabaseException;

public class VerifyDbResource extends Resource {

    private DbMaintenance dbMaintenance;

    public void setDbMaintenance(DbMaintenance dbMaintenance) {
        this.dbMaintenance = dbMaintenance;
    }

    public VerifyDbResource() {
        super();
    }

    @Override
    public void init(Context context, Request request, Response response) {
        super.init(context, request, response);
        getVariants().add(new Variant(MediaType.TEXT_PLAIN));
    }

    @Override
    public Representation getRepresentation(Variant variant) {
        try {
            List<String> errorDbs = dbMaintenance.verify();
            if (errorDbs.isEmpty()) {
                return new StringRepresentation("ok");
            } else {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                for (String db : errorDbs) {
                    pw.println(db);
                }
                return new StringRepresentation(sw.toString());
            }
        } catch (DatabaseException e) {
            throw new RuntimeException(e);
        }
    }
}
